/*
 *  Control 7 segments display using MAXIM MAX7219 driver IC and
 *  Matrix Library
 */
int CLOCK_PIN =2;
int DATA_PIN  =3;
int TR[4] = {
  16,17,18,19,};

int TR1=18;
int TR2=19;

int NONE = 10;

int SEG[4] = {0,0,0,0,};

int NUM[11] = {
  B11111100,  // 0
  B01100000,  // 0
  B11011010,  // 2
  B11110010,  // 3
  B01100110,  // 4
  B10110110,  // 5
  B00111110,  // 6
  B11100000,  // 7 
  B11111110,  // 8
  B11100110,  // 9
  B00000000,  // NONE
};



int value4Display = 9999;

unsigned long lastMillis;
unsigned long currentMillis;
#define NEXTPERIOD 25

#define SWITCH_SEG_PERIOD 250UL
unsigned long switchSegCounter=SWITCH_SEG_PERIOD;
int currentSegID =3 ;



void setup()                    // run once, when the sketch starts
{
  pinMode(CLOCK_PIN, OUTPUT);
  pinMode(DATA_PIN,  OUTPUT);
  for (int i = 0 ; i < 4 ; i++){
    pinMode(TR[i],  OUTPUT);    
    digitalWrite(TR[i], HIGH);
  }

  lastMillis = millis();


}

void loop()                     // run over and over again
{
  currentMillis=millis();
  if ( currentMillis - lastMillis > NEXTPERIOD ) {
    lastMillis = currentMillis;
    updateValue();
    setSegsData();
  }
  
  displayNumbers();

}

void updateValue(){
  value4Display --;
  if ( value4Display < 0 ) {
    value4Display = 9999;
  }
}
void setSegsData() {
  int v = value4Display;
  
  if ( v > 1000 ) {
    SEG[3] = v / 1000;
  } else {
    SEG[3] = 0;
  }
 
  v = v - 1000 * SEG[3]; 
  if ( v > 100 ) {
    SEG[2] = v / 100;
  } else {
    SEG[2] = 0;
  }
  
  v = v - 100 * SEG[2]; 
  if ( v > 10 ) {
    SEG[1] = v / 10;
  } else {
    SEG[1] = 0;
  }
  SEG[0] = v - 10 * SEG[1];
}

void displayNumbers(){
  switchSegCounter++ ;
  if ( switchSegCounter >  SWITCH_SEG_PERIOD ) {
    switchSegCounter=0;
    currentSegID++ ;
    if ( currentSegID > 3) {
      currentSegID = 0 ;
    }
    displayNumber(currentSegID);
  }
}

void displayNumber(int digit) {
  digitalWrite(TR[digit],LOW);
  for (int i = 0 ; i < 4 ; i++){
    if ( i != digit ){
      digitalWrite(TR[i], HIGH);
    }
  }
  shiftOut(DATA_PIN, CLOCK_PIN, LSBFIRST, NUM[SEG[digit]]);
} 


